// pages/users/index.js
const {
  wxLogin,
  wxMobileLogin,
  decodeUserInfo,
  updateUserInfo,
  sysSetting
} = require('../../../api/login')
const {
  uploadPic,
  uploadImage,
  imageToBase64
} = require('../../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sexOptions: ['男', '女'],
    cityOptions: [{
        "id": "110000",
        "name": "北京",
        "cityList": [{
          "id": "110000",
          "name": "北京",
          "cityList": [{
            "id": "110101",
            "name": "东城区"
          }]
        }]
      },
      {
        "id": "110001",
        "name": "湖南",
        "cityList": [{
          "id": "110000",
          "name": "长沙",
          "cityList": [{
            "id": "110101",
            "name": "天心区"
          }]
        }]
      }
    ],
    region: [],
    sex: 0,
    sexIndex:0,
    nickname: '',
    mobile: '',
    avatar: '',
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchUserInfo()
  },
  changeIndex(e) {
    const {
      index,
      type,
    } = e.currentTarget.dataset
    this.setData({
      [type]: index
    })
  },
  async fetchUserInfo() {
    const {
      result
    } = await decodeUserInfo()
    const initCity = wx.getStorageSync('initCity').split(',')
    this.setData({
      nickname: result.nickname,
      mobile: result.mobile,
      sexIndex: result.sex,
      avatar: result.avatar,
      region: result.city ? result.city.split(',') || initCity : initCity
    })
  },
  async getPhoneNumber(e) {
    wx.showLoading({
      title: '授权中',
    })
    const {
      encryptedData,
      iv
    } = e.detail

    wx.login({
      success: async function (res) {
        const param = {
          code: res.code,
          encryptedData,
          iv
        }
        const data = await wxMobileLogin(param)
        wx.hideLoading()
        if (data.success) {
          wx.showToast({
            title: '授权成功',
          })
          this.fetchUserInfo()
        }
      }
    })


  },
  inputChange(e) {
    const type = e.currentTarget.dataset.type
    const isValidPhone = /^[1]([3-9])[0-9]{9}$/.test(e.detail.value);
    if(type=='mobile'&&!isValidPhone&&e.detail.value.length==11){
      wx.showToast({
        title: '手机号不正确',
        icon:'none'
      })  
      return
    }
    this.setData({
      [type]: e.detail.value
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      sex: e.detail.value
    })
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },

  async save(e) {
    const {
      nickname
    } = e.detail.value
    const {
      mobile,
      region,
      sexIndex,
      avatar,
    } = this.data
    const params = {
      mobile,
      nickname,
      city: region.join(','),
      sex: parseInt(sexIndex),
      avatar
    }
    const {
      result
    } = await updateUserInfo(params)
    if (result) {
      wx.showToast({
        title: '更新成功',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 300);
    }
  },
  async onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const img = await uploadPic(avatarUrl)
    this.setData({
      avatar: img,
    })
  },
  chooseImage(e) {
    var that = this;
    const type = e.currentTarget.dataset.type
    var count = 1
    uploadImage(count).then((filePath) => {
      that.setData({
        photoList: filePath
      })
      that.upload()
    })
  },
  async upload() {
    var _this = this
    const {
      picsMap,
      photoList
    } = this.data;
    const img = await uploadPic(photoList[0])
    _this.setData({
      avatar: img,
      photolist: []
    })
    wx.hideLoading()
  },
  gotoIntention() {
    wx.navigateTo({
      url: '/pages/users/index/index',
    })
  }
})